const fs = require('fs')

// @param {*当前页的数量} pageSize
// @param {*当前页} currentPage
// @param {*当前数组} arr
function pagination(pageSize, currentPage, arr) {
  let skipNum = (currentPage - 1) * pageSize;
  let newArr = (skipNum + pageSize >= arr.length) ? arr.slice(skipNum, arr.length) : arr.slice(skipNum, skipNum + pageSize);
  return newArr;
}

// 升序还是降序
function sortBy(attr, rev) {
  if (rev === undefined) {
    rev = 1;
  } else {
    rev = rev ? 1 : -1;
  }
  return function (a, b) {
    a = a[attr];
    b = b[attr];
    if (a < b) {
      return rev * -1;
    }
    if (a > b) {
      return rev * 1;
    }
    return 0;
  }
}

function range(arr, gt, lte) {
  return arr.filter(item => item.salePrice >= gt && item.salePrice <= lte)
}

const cors = require('cors')
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser')
module.exports = {
  devServer: {
    open: true,
    port: 8082,
    host: '0.0.0.0',
    // !--模拟数据开始-- >
    before(app, serve) {
      app.use(cors())
      app.use(bodyParser.json())
      app.use(bodyParser.urlencoded({
        extended: false
      }))
      // home数据
      app.get('/api/goods/home', (req, res) => {
        fs.readFile('./public/mock/home.json', 'utf8', (err, data) => {
          if (!err) {
            res.json(JSON.parse(data))
          }
        })
      })
      // 全部
      app.get('/api/goods/allGoods', (req, res) => {
        const page = parseInt(req.query.page);
        const size = parseInt(req.query.size);
        const sort = parseInt(req.query.sort);
        const gt = parseInt(req.query.priceGt);
        const lte = parseInt(req.query.priceLte);
        const cid = req.query.cid;
        let newData = []
        fs.readFile('./public/mock/allGoods.json', 'utf8', (err, data) => {
          let {
            result
          } = JSON.parse(data);
          let allData = result.data;
          // 分页显示
          newData = pagination(size, page, allData);
          if (cid === '1184') {
            if (sort === 1) {
              // 价格由低到高
              newData = newData.sort(sortBy('salePrice', true))
            } else if (sort === -1) {
              // 价格由高到低
              newData = newData.sort(sortBy('salePrice', false))
            }
          } else {
            if (sort === 1) {
              // 价格由低到高
              newData = newData.sort(sortBy('salePrice', true))
            } else if (sort === -1) {
              // 价格由高到低
              newData = newData.sort(sortBy('salePrice', false))

            }
            if (gt && lte) {
              // 过滤 10-1000
              newData = range(newData, gt, lte)
            }
          }
          if (newData.length < size) {
            res.json({
              data: newData,
              total: newData.length
            })
          } else {
            res.json({
              data: newData,
              total: allData.length
            })
          }
        })



      })
      // 商品详情
      app.get('/api/goods/productDet', (req, res) => {
        const productId = req.query.productId
        fs.readFile('./public/mock/goodsDetail.json', 'utf8', (err, data) => {
          if (!err) {
            let {
              result
            } = JSON.parse(data)
            let newData = result.find(item => item.productId == productId)
            res.json(newData)
          }
        })
      })
      // 模拟登录接口
      app.post('/api/login', (req, res) => {
        console.log(req.body.user);
        // 登陆成功用户名
        let username = req.body.user
        // 一系列操作
        res.json({
          // 进行加密的方法
          // sing 参数一: 加密的对象 参数二：加密的规则
          token: jwt.sign({
            username: username
          }, 'abcd', {
            expiresIn: "3000s"
          }),
          username,
          state: 1,
          file: '@/assets/img/logo1.png',
          code: 200,
          address: null,
          balance: null,
          description: null,
          email: null,
          message: null,
          phone: null,
          points: null,
          sex: null,
          id: 62
        })
      })
      // d登录持久化验证接口，，访问这个接口的时候，一定要访问token
      app.post('/api/validate', function (req, res) {
        let token = req.headers.authorization
        // 验证token合法，对token进行解码
        jwt.verify(token, 'abcd', function (err, decode) {
          if (err) {
            res.json({
              msg: '当前用户未登录'
            })
          } else {
            // 验证用户已登录
            res.json({
              token: jwt.sign({
                username: decode.username
              }, 'abcd', {
                expiresIn: "3000s"
              }),
              username: decode.username,
              msg: '已登录',
              address: null,
              balance: null,
              description: null,
              email: null,
              file: "@/assets/img/logo1.png",
              id: 62,
              message: null,
              phone: null,
              points: null,
              sex: null,
              state: 1
            })
          }
        })

      })
      app.post('/api/addCart', (req, res) => {
        let {
          userId,
          productId,
          productNum
        } = req.body;
        fs.readFile('。/public/mock/allGoods.json', (err, data) => {
          console.log('post api/addCart...');
          console.log(data);
          let {
            result
          } = JSON.parse(data);
          if (productId && userId) {
            let {
              cartList
            } = cartListJSON.result.find(item => item.id == userId)
            console.log('add cartList');
            console.log(cartList);
            // 找到对应的商品
            let newData = result.data.find(item => item.productId == productId);
            newData.limitNum = 100;
            console.log('newData');
            console.log(newData);

            let flag = true;
            if (cartList && cartList.length) {
              cartList.forEach(item => {
                if (item.productId == productId) {
                  if (item.productNum >= 1) {
                    flag = false;
                    item.productNum += parseInt(productNum);
                  }
                }
              })
            }
            if (!cartList.length || flag) { //购物车为空
              newData.productNum = parseInt(productNum)
              cartList.push(newData);
            }

            // 序列化
            console.log('序列化');
            fs.writeFile('./public/mock/cartList.json', JSON.stringify(cartListJSON), (err) => {
              if (!err) {
                console.log('序列化成功！');
                res.json({
                  code: 200,
                  message: "success",
                  result: 1,
                  success: true,
                  timestamp: 1571296313981,
                })
              }
            })
          }

        })

      })
    }
  },
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/'
}
